import { Matrix4, PerspectiveCamera, OrthographicCamera, Vector3 } from "three";
import CameraController from "../component/CameraController.js";

interface CameraData {
    eye: Vector3;
    lookAt: Vector3;
    canvas: HTMLCanvasElement;
}

export default class Camera {
    private eye: Vector3;
    private lookAt: Vector3;
    private canvas: HTMLCanvasElement;

    private pvM4: Matrix4 = new Matrix4();


    public constructor(data: CameraData) {

        this.eye = data.eye;
        this.lookAt = data.lookAt;
        this.canvas = data.canvas;

        this.pvM4 = this.updatePvM4();
    }

    public setPvM4(eye: Vector3, lookAt: Vector3) {
        this.eye.copy(eye);
        this.lookAt.copy(lookAt);
        return this.updatePvM4();
    }

    public updatePvM4() {
        const { eye, lookAt, canvas } = this;

        const eyem = new Matrix4().setPosition(eye.x, eye.y, eye.z);
        const lookAtm = new Matrix4().lookAt(
            eye, lookAt, new Vector3(0, 1, 0)
        );
        const viewm = (eyem.multiply(lookAtm)).invert();

        const viewH = 2;//设定视图矩阵高度  
        const wh = canvas.width / canvas.height;
        const viewW = viewH * wh;//求视图矩阵宽度  
        const [l, r, t, b, q, h] = [
            -viewW, viewW, viewH, -viewH, -10, 10
        ];
        const projectionm = new Matrix4().makeOrthographic(l, r, t, b, q, h);
        return this.pvM4.copy(projectionm.multiply(viewm));

        // const camera = new PerspectiveCamera(45, canvas.width / canvas.height, 1, 20);
        // const cameraController = new CameraController({
        //     canvas: canvas,
        //     camera,
        //     pvMatrix: this.pvM4,
        //     eye,
        //     lookAt,
        // });
        // return this.pvM4;

    }

    public getPvM4(isUpdate: boolean = false) {
        if (isUpdate) {
            return this.updatePvM4();
        }
        return this.pvM4;
    }


}